# apps/users/tests.py
from django.contrib.auth import get_user_model
from django.urls import reverse
from rest_framework.test import APITestCase
from rest_framework import status

User = get_user_model()

class UserTestCase(APITestCase):
    def setUp(self):
        self.admin = User.objects.create_superuser(
            username='admin',
            password='admin123',
            email='admin@test.com'
        )
        self.user = User.objects.create_user(
            username='testuser',
            password='test123',
            full_name='Test User',
            role='teacher'
        )

    def test_create_user(self):
        """测试创建用户"""
        url = reverse('user-list')
        data = {
            'username': 'newuser',
            'password': 'newpass123',
            'full_name': 'New User',
            'email': 'new@test.com',
            'role': 'student',
            'tenant': 1
        }
        self.client.force_authenticate(user=self.admin)
        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(User.objects.count(), 3)
        self.assertEqual(User.objects.last().username, 'newuser')

    def test_user_me_endpoint(self):
        """测试获取当前用户信息"""
        url = reverse('user-me')  # basename-action_name
        # 方法 1：force_authenticate（推荐用于 API 测试）
        self.client.force_authenticate(user=self.user)

        # 方法 2：真实登录（模拟浏览器行为）
        self.client.login(username='testuser', password='testpass123')
        response = self.client.get(url)
        # 👇 打印响应内容，看看到底为什么 403
        print("Status Code:", response.status_code)
        print("Response Data:", response.data)  # 这里会告诉我们真相
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data['username'], 'testuser')

    def test_only_admin_can_create_user(self):
        """测试仅管理员可创建用户"""
        url = reverse('user-list')
        data = {'username': 'hacker', 'password': '123'}
        self.client.force_authenticate(user=self.user)  # 普通用户
        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)